import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:reabampos/src/reabam/operation/bean/base/rb_response.dart';
import 'package:reabampos/src/reabam/operation/bean/socket/Request_update_serversocket.dart';
import 'package:reabampos/src/reabam/operation/rb_api.dart';
import 'package:reabampos/src/reabam/operation/rb_config.dart';
import 'package:reabampos/src/reabam/operation/rb_enum.dart';
import 'package:reabampos/src/reabam/ui/setting/pagestate_edit_device.dart';
import 'package:reabampos/src/reabam/ui/setting/pagestate_scan_ble_device.dart';
import 'package:reabampos/src/reabam/ui/setting/pagestate_scan_usb_device.dart';
import 'package:reabampos/src/reabam/ui/setting/pagestate_scan_usb_serial_device.dart';
import 'package:reabampos/src/reabam/ui/setting/pagestate_select_device_pinpai.dart';
import 'package:reabampos/src/reabam/ui/setting/pagestate_server_ip_list.dart';
import 'package:reabampos/src/reabam/ui/setting/pagestate_socket_printer_setting.dart';
import 'package:reabampos/src/reabam/utils/rb_color.dart';
import 'package:reabampos/src/reabam/utils/rb_style.dart';
import 'package:reabampos/src/reabam/utils/rb_widget_ss.dart';
import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';
import 'package:xsdk_flutter_plugin/xsdk_flutter_plugin.dart';

/*
设备管理
1.蓝牙设备(打印机,电子秤),只支持android,iOS
2.网络打印,支持android,iOS,window,mac
3.usb打印,只支持android


 */
class DeviceSettingStatePage extends XPageState {
  DeviceSettingStatePage();

  List<XBaseDevice> printerList_bluetooth = [];
  List<XBaseDevice> printerList_socket = [];
  List<XBaseDevice> printerList_cloudDevice = [];
  List<XBaseDevice> printerList_usb = [];
  String? macAddress;

  int timeUsbWeigher = 0;

  @override
  Widget getBodyWidget(BuildContext context) {
    List<Widget> children = [];

    if (RBConfigs.versionType == VersionType.officialSelfServiceVersion ||
        RBConfigs.versionType == VersionType.testSelfServiceVersion) {
      //自助收银
      if (XFlutterUtils.isAndroid()) {
        //usb打印机
        children.add(_getWidget_printer_bar_usb());
      }
    } else {
      //睿本云HD 横屏

      //叫号屏
      children.add(_createWidget_tv_bar());

      //电子秤
      if (XFlutterUtils.isAndroid()) {
        //商米内置打印
        if (RBConfigs.isShangMiDevice) {
          children.add(_getWidget_printer_bar_Shangmi());
          children.add(_getWidget_serial_weigher_bar_Shangmi());
        }

        //usb串口电子秤
        children.add(_createWidget_weigher_bar_usb());
        //蓝牙电子秤
        children.add(_createWidget_weigher_bar_bluetooth());
      } else if (XFlutterUtils.isiOS()) {
        //蓝牙电子秤
        children.add(_createWidget_weigher_bar_bluetooth());
      } else if (XFlutterUtils.isMacOS()) {
        //蓝牙电子秤
        children.add(_createWidget_weigher_bar_bluetooth());
      }

      //多端打印
      children.add(_getWidget_socket_server_client_printer());

      //打印机
      String companyId =
          XSharePreferencesUtils.getString(RBConfigs.SP_companyId);
      bool isUseServerClientSocketPrinter = XSharePreferencesUtils.getBool(
          '${RBConfigs.SP_isUseServerClientSocketPrinter}$companyId');
      String currentSocketServerOrClient = XSharePreferencesUtils.getString(
          '${RBConfigs.SP_currentServerOrClientSoscketPrinter}$companyId');

      if (!isUseServerClientSocketPrinter ||
          (isUseServerClientSocketPrinter &&
              currentSocketServerOrClient == '主设备')) {
        if (XFlutterUtils.isAndroid()) {
          //usb打印机
          children.add(_getWidget_printer_bar_usb());
          //蓝牙打印机
          children.add(_getWidget_printer_bar_bluetooth());
        } else if (XFlutterUtils.isiOS()) {
          //蓝牙打印机
          children.add(_getWidget_printer_bar_bluetooth());
        } else if (XFlutterUtils.isMacOS()) {
          //蓝牙打印机
          //children.add(_getWidget_printer_bar_bluetooth());
        }

        //网络打印机
        children.add(_getWidget_printer_bar_ip());
        //快麦云打印机
        children.add(_getWidget_printer_bar_kuaimaiCloudPrint());
      }
    }

    return XWidgetUtils.getLayoutSingleChildScrollView(
        child: XWidgetUtils.getLayoutColumn(children: children));
  }

  @override
  void onCreate() async {
    super.onCreate();

    RBConfigs.localIP ??= await XWifiUtils.getWifiIP();
    XLogUtils.printLog('---localIP:${RBConfigs.localIP}');
    macAddress = await XMacAddressUtils.getMacAddress();
    XLogUtils.printLog('---macAddress:$macAddress');

    clientSocketDeviceConnectListener = (
      bool isConnect,
      String? ip,
      int? port,
    ) {
      setState(() {
        //XLogUtils.printLog('---监听client socket');
      });
    };
    serverSocketListener = (
      int currentClientSocketsCount,
    ) {
      setState(() {
        //XLogUtils.printLog('---server socket');
      });
    };

    XSocketUtils.addClientSocketDeviceConnectListener(
        clientSocketDeviceConnectListener);
    XSocketUtils.addServerSocketDeviceConnectListener(serverSocketListener);

    bleDeviceConnectListener = (bool isConnect, String deviceAddress) {
      setState(() {});
    };
    XBluetoothBLEUtils.addBleDeviceConnectListener(bleDeviceConnectListener);
  }

  late XFunctionClientSocketDeviceConnectListener
      clientSocketDeviceConnectListener;
  late XFunctionServerSocketListener serverSocketListener;
  late XFunctionBleDeviceConnectListener bleDeviceConnectListener;

  @override
  void onDestroy() {
    super.onDestroy();
    XSocketUtils.removeClientSocketDeviceConnectListener(
        clientSocketDeviceConnectListener);
    XSocketUtils.removeServerSocketDeviceConnectListener(serverSocketListener);
    XBluetoothBLEUtils.removeBleDeviceConnectListener(bleDeviceConnectListener);
    XUsbSerialUtils.disconnectUsbSerialDevice();
  }

  @override
  void onStart() {
    XLogUtils.printLog(
        '---deviceInfo=${XJsonUtils.obj2Json(XTempData.deviceInfo)}');

    if (RBConfigs.versionType == VersionType.officialSelfServiceVersion ||
        RBConfigs.versionType == VersionType.testSelfServiceVersion) {
      //自助收银
      setXTopBarWidget(
          height: null,
          child: RBWidgets_SelfService.getTitleBarWidget(
            this,
            title: '设备管理',
          ));
    } else {
      //HD h5
      setXTitle(titleText: '设备管理', titleBarHeight: 50, isShowLeftWidget: false);
      setXLeftFixSpace(
        width: 458,
      );
    }
  }

  @override
  void finishPage({result, String? backToPointPageName}) {
    animationControllerMengcheng?.reverse();
    //
    XFlutterUtils.finishPage(context,
        result: 'ok', backToPointPageName: backToPointPageName);
  }

  @override
  Future<void> updateData({int pageIndex = 1}) async {
    setState(() {
      //更新蓝牙打印机
      _updateBluetoothDevice();
      //更新socket设备
      _updateSocketDevice();
      //更新远程设备
      _updateRemotePrintDevice();
      //更新usb设备
      _updateUsbDevice();
      //更新useSerial设备
      _updateUsbSerialDevice();
    });
  }

  ////////////////////////////////////////////////////

  //多端打印
  Widget _getWidget_socket_server_client_printer() {
    String companyId = XSharePreferencesUtils.getString(RBConfigs.SP_companyId);
    bool isUseServerClientSocketPrinter = XSharePreferencesUtils.getBool(
        '${RBConfigs.SP_isUseServerClientSocketPrinter}$companyId');
    String currentSocketServerOrClient = XSharePreferencesUtils.getString(
        '${RBConfigs.SP_currentServerOrClientSoscketPrinter}$companyId');

    return XWidgetUtils.getLayoutContainer(
        margin: XWidgetUtils.getEdgeInsets(XTempData.defaultPageMarginLeft, 10,
            XTempData.defaultPageMarginRight, 0),
        alignment: Alignment.center,
        decoration: XWidgetUtils.getBoxDecoration(
            backgroundColor: Colors.white,
            //border: Border.all(width: 0.5, color: XColorUtils.dividerColor),
            borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(10),
              topRight: Radius.circular(10),
              bottomLeft: Radius.circular(10),
              bottomRight: Radius.circular(10),
            )),
        child: XWidgetUtils.getLayoutColumn(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              XWidgetUtils.getXBarForLeftRightDefault(
                leftText: '多端打印 (本机IP:${RBConfigs.localIP})',
                rightText: '',
                rightWidget: XWidgetUtils.getWidgetSwitch(
                    currentValue: isUseServerClientSocketPrinter,
                    onChanged: (bool value) {
                      //
                      XSharePreferencesUtils.saveBool(
                          '${RBConfigs.SP_isUseServerClientSocketPrinter}$companyId',
                          value);
                      //
                      if (value) {
                        //启用...
                        if ('主设备' == currentSocketServerOrClient) {
                          _enableServerSocketPrinter(true);
                        } else if ('子设备' == currentSocketServerOrClient) {
                          //由于已删除子设备记录,需要手动重新设置ok
                        }
                      } else {
                        //停用
                        //删除主设备和子设备
                        XSharePreferencesUtils.saveString(
                            '${RBConfigs.SP_currentServerOrClientSoscketPrinter}$companyId',
                            '');
                        XSocketUtils.removeServerSocketDevice();
                        XSocketUtils.removeClientSocketDeviceByType(
                            RBConfigs.ClientSocketPrinter);
                      }

                      setState(() {
                        _updateSocketDevice();
                      });
                    }),
                isShowBottomDivider: false,
              ),
              XWidgetUtils.getLayoutVisibility(
                isVisible: isUseServerClientSocketPrinter,
                child: XWidgetUtils.getLayoutColumn(children: [
                  XWidgetUtils.getXBarForLeftRightDefault(
                    leftText: '设备类型',
                    rightText: '',
                    rightWidget:
                        _getSelectServerOrClientSocketPrinterWidget(), //选择socket主设备or子设备
                    isShowTopDivider: true,
                    isShowBottomDivider: false,
                  ),
                  XWidgetUtils.getLayoutVisibility(
                      isVisible:
                          '主设备' == currentSocketServerOrClient ? true : false,
                      child: XWidgetUtils.getXBarForLeftRightDefault(
                          leftText:
                              '主设备 (子设备连接数:${XSocketUtils.serverSocketAPI?.clientSockets.length ?? 0})',
                          rightText: '更新上传',
                          rightTextStyle:
                              RBStyles.textStyle_reabamColor4_defaultSize(),
                          isShowTopDivider: true,
                          isShowBottomDivider: false,
                          onPressed: () {
                            //更新服务端数据
                            _updateServerSocketInfo();
                          })),
                  XWidgetUtils.getLayoutVisibility(
                      isVisible:
                          '子设备' == currentSocketServerOrClient ? true : false,
                      child: XWidgetUtils.getXBarForLeftRightDefault(
                          leftText: clientSocketPrinter == null
                              ? '未绑定主设备IP'
                              : '绑定主设备IP: ${clientSocketPrinter?.ip}',
                          rightText: '',
                          rightWidget: XWidgetUtils.getLayoutRow(children: [
                            clientSocketPrinter == null
                                ? XWidgetUtils.getLayoutContainer()
                                : XWidgetUtils.getWidgetGestureDetector(
                                    child: XWidgetUtils.getWidgetText(
                                        clientSocketPrinter!.isConnected
                                            ? '测试'
                                            : '(正在连接中)',
                                        padding: XWidgetUtils.getEdgeInsets(
                                            35, 0, 10, 0),
                                        style: XStyleUtils.getTextStyle(
                                            fontSize:
                                                XTempData.defaultTextFontSize,
                                            color:
                                                clientSocketPrinter!.isConnected
                                                    ? RBColors.reabamColor4
                                                    : XColorUtils.color999999)),
                                    onTap: () {
                                      //测试
                                      XLogUtils.printLog('---多端打印子设备测试');
                                      Map<String, dynamic> socketMap = {};
                                      socketMap['type'] =
                                          'XClientSocketTestPrint';

                                      XBaseQueueMessage socketMsg =
                                          XBaseQueueMessage(
                                        msgId:
                                            '多端打印子设备测试_${XDateUtils.getCurrentTime_ms()}',
                                        message: socketMap,
                                        ip: clientSocketPrinter!.ip,
                                        port: clientSocketPrinter!.port,
                                      );
                                      XSocketUtils.sendMsgToQueue(socketMsg);
                                    }),
                            XWidgetUtils.getWidgetGestureDetector(
                                child: XWidgetUtils.getWidgetText(
                                    clientSocketPrinter == null ? '获取' : '重新获取',
                                    padding:
                                        XWidgetUtils.getEdgeInsets(10, 0, 5, 0),
                                    style: XStyleUtils.getTextStyle(
                                        fontSize: XTempData.defaultTextFontSize,
                                        color: RBColors.reabamColor4)),
                                onTap: () {
                                  startPage(SocketServerIPListStatePage(),
                                      resultCallback: (dynamic result) {
                                    if (result != null) {
                                      String selectServerIP = result as String;

                                      //1.删除旧的客户端
                                      XSocketUtils
                                          .removeClientSocketDeviceByType(
                                              RBConfigs.ClientSocketPrinter);
                                      //2.添加新的客户端
                                      XBaseDevice clientSocketDevice =
                                          XBaseDevice();
                                      clientSocketDevice.ip = selectServerIP;
                                      clientSocketDevice.port = 2222;
                                      clientSocketDevice.customType =
                                          RBConfigs.ClientSocketPrinter;
                                      clientSocketDevice
                                          .isCustomSocketCommunication = true;
                                      XSocketUtils.addDevice(
                                          clientSocketDevice);
                                      //3.更新ui
                                      setState(() {
                                        _updateSocketDevice();
                                      });
                                    }
                                  });
                                }),
                            XImageUtils.getImageWidgetWithAsset(
                                'nav_arrow_right.png',
                                width: RBConfigs.image_nav_arrow_right_width,
                                height: RBConfigs.image_nav_arrow_right_height)
                          ]),
                          isShowTopDivider: true,
                          isShowBottomDivider: false)),
                ]),
              ),
              XWidgetUtils.getLayoutVisibility(
                isVisible: isUseServerClientSocketPrinter,
                child: XWidgetUtils.getXBarForLeftRightDefault(
                  leftText: '指定打印机',
                  rightText: '设置',
                  rightTextStyle: XStyleUtils.getTextStyle(
                      fontSize: XTempData.defaultTextFontSize,
                      color: RBColors.reabamColor4),
                  rightWidget: XImageUtils.getImageWidgetWithAsset(
                      'nav_arrow_right.png',
                      width: RBConfigs.image_nav_arrow_right_width,
                      height: RBConfigs.image_nav_arrow_right_height),
                  isShowBottomDivider: false,
                  onPressed: () {
                    startPage(SocketPrinterSettingStatePage(),
                        resultCallback: (dynamic result) {
                      if (result != null) {}
                    });
                  },
                ),
              ),
            ]));
  }

  //启用主socket或子socket打印机
  void _enableServerSocketPrinter(bool isEnable) {
    if (isEnable) {
      //开启ServerSocketPrinter
      //1.关闭和删除ClientSocketPrinter
      XSocketUtils.removeClientSocketDeviceByType(
          RBConfigs.ClientSocketPrinter);
      //2.开启服务端socket
      XBaseDevice serverSocketDevice = XBaseDevice();
      serverSocketDevice.port = 2222;
      serverSocketDevice.isServerSocket = true;
      serverSocketDevice.customType = RBConfigs.ServerSocketPrinter;
      XSocketUtils.addDevice(serverSocketDevice);
      //3.更新服务端数据
      _updateServerSocketInfo();
    } else {
      //关闭和删除服务端socket
      XSocketUtils.removeServerSocketDevice();
    }
  }

  //上传更新服务端socket
  void _updateServerSocketInfo() {
    List<BeanSocketPrintSetDTOS> printSetDTOS = [];
    BeanSocketPrintSetDTOS item = BeanSocketPrintSetDTOS();
    item.isMain = 1;
    item.companyId = XSharePreferencesUtils.getString(RBConfigs.SP_companyId);
    item.ip = RBConfigs.localIP;
    item.mac = macAddress;
    printSetDTOS.add(item);
    RBBaseApi.updateServerSocketInfo(
        printSetDTOS: printSetDTOS,
        succeed: (RBBaseResponse response, Map<String, dynamic> responseMap,
            Map<String, dynamic> headers_response) {
          XLogUtils.printLog('---更新服务端socket成功');
          toast("更新主设备IP成功!");
        },
        failed: (String code, String msg) {
          XLogUtils.printLog('---更新服务端socket失败: $code,$msg');
          toast(msg);
        });
  }

  //socket主设备子设备选择

  Widget _getSelectServerOrClientSocketPrinterWidget() {
    String companyId = XSharePreferencesUtils.getString(RBConfigs.SP_companyId);
    String currentSocketServerOrClient = XSharePreferencesUtils.getString(
        '${RBConfigs.SP_currentServerOrClientSoscketPrinter}$companyId');

    return XWidgetUtils.getLayoutRow(children: [
      XWidgetUtils.getWidgetRadio(
          currentSelectValue: currentSocketServerOrClient,
          labelValue: '主设备',
          onChanged: (String? value) {
            //启用主socket或子socket打印机
            _enableServerSocketPrinter(true);
            setState(() {
              XSharePreferencesUtils.saveString(
                  '${RBConfigs.SP_currentServerOrClientSoscketPrinter}$companyId',
                  value ?? '');
            });
          },
          showText: '主设备'),
      XWidgetUtils.getWidgetRadio(
          currentSelectValue: currentSocketServerOrClient,
          labelValue: '子设备',
          onChanged: (String? value) {
            //启用主socket或子socket打印机
            _enableServerSocketPrinter(false);
            //清除已设置的打印机
            XBluetoothBLEUtils.removeDeviceByType(RBConfigs.BluetoothPrinter);
            XUsbUtils.removeNoteUsbDeviceByType(RBConfigs.USBPrinter);
            XSocketUtils.removeClientSocketDeviceByType(RBConfigs.IPPrinter);
            XRemoteDeviceUtils.removeDeviceByType(RBConfigs.CloudPrinter);
            XSharePreferencesUtils.saveString(
                '${RBConfigs.SP_currentServerOrClientSoscketPrinter}$companyId',
                value ?? '');

            updateData();
          },
          showText: '子设备'),
    ]);
  }

  Widget _createWidget_tv_bar() {
    return XWidgetUtils.getXLayoutRoundedRect(
        margin: XWidgetUtils.getEdgeInsets(XTempData.defaultPageMarginLeft, 10,
            XTempData.defaultPageMarginRight, 0),
        child: XWidgetUtils.getLayoutColumn(children: [
          XWidgetUtils.getXBarForLeftRightDefault(
            leftText: '叫号屏',
            rightText: socketTV == null ? '添加设备' : '修改设备',
            rightTextStyle: XStyleUtils.getTextStyle(
                fontSize: XTempData.defaultTextFontSize,
                color: RBColors.reabamColor4),
            rightWidget: XImageUtils.getImageWidgetWithAsset(
                'nav_arrow_right.png',
                width: RBConfigs.image_nav_arrow_right_width,
                height: RBConfigs.image_nav_arrow_right_height),
            isShowBottomDivider: false,
            onPressed: () {
              XFlutterUtils.openDialogWithTextField(
                context: context,
                width: RBConfigs.dialogWidth,
                title: '设置叫号屏IP',
                defaultTextValue: '',
                hintText: '请输入ip地址',
                onCallbackResult: (Map<String, dynamic>? result) {
                  String key = result!['key'];
                  if (key == '确定') {
                    String value = result['value'];
                    XLogUtils.printLog('---value=$value');

                    //断开原来的连接
                    XSocketUtils.removeClientSocketDeviceByType(
                        RBConfigs.SocketTV);

                    //
                    XBaseDevice socketTv = XBaseDevice(
                      ip: value,
                      port: 2221,
                      customType: RBConfigs.SocketTV,
                    );
                    XSocketUtils.addDevice(socketTv);

                    setState(() {
                      _updateSocketDevice();
                    });
                  }
                },
              );
            },
          ),
          XWidgetUtils.getLayoutVisibility(
            isVisible: socketTV != null,
            child: XWidgetUtils.getXBarForLeftRightWidget(
              leftWidget: socketTV == null
                  ? const Text('')
                  : XWidgetUtils.getLayoutExpanded(XWidgetUtils.getWidgetText(
                      '${socketTV!.ip}',
                      style: XStyleUtils.getTextStyle(
                          fontSize: XTempData.defaultTextFontSize,
                          color: XColorUtils.color333333))),
              rightWidget: XWidgetUtils.getLayoutRow(children: [
                XWidgetUtils.getWidgetButtonText(
                    text: '删除',
                    buttonStyle:
                        RBStyles.buttonStyle_reabamColor4_defaultSize(),
                    onPressed: () {
                      XSocketUtils.removeClientSocketDeviceByType(
                          RBConfigs.SocketTV);
                      //更新ui
                      setState(() {
                        _updateSocketDevice();
                      });
                    }),
                XWidgetUtils.getWidgetButtonText(
                    text: socketTV?.isConnected == true ? '测试' : '(正在连接中)',
                    buttonStyle: socketTV?.isConnected == true
                        ? RBStyles.buttonStyle_reabamColor4_defaultSize()
                        : XStyleUtils.getButtonStyle(
                            fontColor: XColorUtils.color999999,
                            fontSize: XTempData.defaultTextFontSize),
                    onPressed: () {
                      if (socketTV != null) {
                        Map testMsg = {
                          'msgType': 'baiduTTS',
                          'speakMsg': '叫号屏测试',
                        };
                        XBaseQueueMessage msg = XBaseQueueMessage(
                            msgId: '叫号屏测试_${XDateUtils.getCurrentTime_ms()}',
                            message: testMsg,
                            ip: socketTV!.ip!,
                            port: socketTV!.port);
                        XSocketUtils.sendMsgToQueue(msg);
                      }
                    }),
              ]),
              isShowBottomDivider: false,
              isShowTopDivider: true,
            ),
          )
        ]));
  }

  XBaseDevice? socketTV;
  XBaseDevice? clientSocketPrinter;

  void _updateSocketDevice() {
    //
    printerList_socket.clear();
    socketTV = null;
    clientSocketPrinter = null;
    Set<XBaseDevice> connectedDeviceList = XSocketUtils.socketDeviceList;
    XLogUtils.printLog('---socket size=${connectedDeviceList.length}');
    for (XBaseDevice item in connectedDeviceList) {
      if (RBConfigs.SocketTV == item.customType) {
        socketTV = item;
      } else if (RBConfigs.IPPrinter == item.customType) {
        printerList_socket.add(item);
      } else if (RBConfigs.ClientSocketPrinter == item.customType) {
        clientSocketPrinter = item;
      }
    }
  }

  //快麦云打印
  void _updateRemotePrintDevice() {
    //
    printerList_cloudDevice.clear();
    Set<XBaseDevice> connectedDeviceList = XRemoteDeviceUtils.remoteDeviceList;
    XLogUtils.printLog('---云设备 size=${connectedDeviceList.length}');
    for (XBaseDevice item in connectedDeviceList) {
      printerList_cloudDevice.add(item);
    }
  }

  //蓝牙电子秤
  XBaseDevice? weigher_bluetooth;
  Widget _createWidget_weigher_bar_bluetooth() {
    return XWidgetUtils.getXLayoutRoundedRect(
        margin: XWidgetUtils.getEdgeInsets(XTempData.defaultPageMarginLeft, 10,
            XTempData.defaultPageMarginRight, 0),
        child: XWidgetUtils.getLayoutColumn(children: [
          XWidgetUtils.getXBarForLeftRightDefault(
            leftText: '蓝牙电子秤',
            rightText: weigher_bluetooth == null ? '添加设备' : '修改设备',
            rightTextStyle: XStyleUtils.getTextStyle(
                fontSize: XTempData.defaultTextFontSize,
                color: RBColors.reabamColor4),
            rightWidget: XImageUtils.getImageWidgetWithAsset(
                'nav_arrow_right.png',
                width: RBConfigs.image_nav_arrow_right_width,
                height: RBConfigs.image_nav_arrow_right_height),
            isShowBottomDivider: false,
            onPressed: () {
              //跳转扫描界面

              toast('暂未开通此功能');

              // startPage(
              //     ScanBleDeviceStatePage(),
              //     resultCallback:(dynamic result){
              //       //返回扫描选择的蓝牙设备
              //       if(result!=null){
              //
              //         //删除旧设备
              //         if(weigher_bluetooth!=null){
              //           XBluetoothBLEUtils.removeDevice(weigher_bluetooth!.bluetoothAddress!);
              //         }
              //
              //         //添加新设备
              //         XBaseDevice device=result;
              //         device.customType=RBConfigs.BluetoothWeigher;
              //         //连接设备
              //         XBluetoothBLEUtils.addDevice(device);
              //
              //         //更新ui
              //         setState(() {
              //           _updateBluetoothDevice();
              //         });
              //       }
              //     }
              // );
            },
          ),
          XWidgetUtils.getLayoutVisibility(
              isVisible: weigher_bluetooth == null ? false : true,
              child: XWidgetUtils.getXBarForLeftRightWidget(
                leftWidget: weigher_bluetooth == null
                    ? const Text('')
                    : XWidgetUtils.getLayoutExpanded(XWidgetUtils.getWidgetText(
                        '${weigher_bluetooth!.deviceName} ${weigher_bluetooth!.isConnected ? "" : "(正在连接中)"}',
                        style: XStyleUtils.getTextStyle(
                            fontSize: XTempData.defaultTextFontSize,
                            color: XColorUtils.color333333))),
                rightWidget: XWidgetUtils.getLayoutRow(children: [
                  XWidgetUtils.getWidgetButtonText(
                      text: '删除',
                      buttonStyle:
                          RBStyles.buttonStyle_reabamColor4_defaultSize(),
                      onPressed: () {
                        if (weigher_bluetooth != null) {
                          XBluetoothBLEUtils.removeDevice(
                              weigher_bluetooth!.bluetoothAddress!);
                        }
                        //更新ui
                        setState(() {
                          _updateBluetoothDevice();
                        });
                      }),
                ]),
                isShowBottomDivider: false,
                isShowTopDivider: true,
              )),
        ]));
  }

  //usb串口电子秤
  String? value_weigher_usb;

  XBaseDevice? weigher_usb;
  Widget _createWidget_weigher_bar_usb() {
    return XWidgetUtils.getXLayoutRoundedRect(
        margin: XWidgetUtils.getEdgeInsets(XTempData.defaultPageMarginLeft, 10,
            XTempData.defaultPageMarginRight, 0),
        child: XWidgetUtils.getLayoutColumn(children: [
          XWidgetUtils.getXBarForLeftRightDefault(
            leftText: 'USB串口电子秤',
            rightText: weigher_usb == null ? '添加设备' : '修改设备',
            rightTextStyle: XStyleUtils.getTextStyle(
                fontSize: XTempData.defaultTextFontSize,
                color: RBColors.reabamColor4),
            rightWidget: XImageUtils.getImageWidgetWithAsset(
                'nav_arrow_right.png',
                width: RBConfigs.image_nav_arrow_right_width,
                height: RBConfigs.image_nav_arrow_right_height),
            isShowBottomDivider: false,
            onPressed: () {
              startPage(
                  ScanUsbSerialDeviceStatePage(RBConfigs.UsbSerialWeigher),
                  resultCallback: (dynamic result) {
                //返回扫描选择的蓝牙设备
                if (result != null) {
                  //更新ui
                  setState(() {
                    value_weigher_usb = null;
                    XUsbSerialUtils.disconnectUsbSerialDevice();
                    _updateUsbSerialDevice();
                  });
                }
              });
            },
          ),
          XWidgetUtils.getLayoutVisibility(
              isVisible: weigher_usb == null ? false : true,
              child: XWidgetUtils.getXBarForLeftRightWidget(
                leftWidget: weigher_usb == null
                    ? XWidgetUtils.getLayoutContainer()
                    : XWidgetUtils.getLayoutExpanded(XWidgetUtils.getWidgetText(
                        XStringUtils.isEmpty(weigher_usb!.brand)
                            ? weigher_usb!.deviceName!
                            : '${weigher_usb!.deviceName}(${weigher_usb!.brand})',
                        style: XStyleUtils.getTextStyle(
                            fontSize: XTempData.defaultTextFontSize,
                            color: XColorUtils.color333333))),
                rightWidget: XWidgetUtils.getLayoutRow(children: [
                  XWidgetUtils.getWidgetGestureDetector(
                      child: XWidgetUtils.getLayoutContainer(
                          backgroundColor: Colors.white,
                          padding: XWidgetUtils.getEdgeInsets(10, 0, 10, 0),
                          child: XWidgetUtils.getWidgetText(
                            XStringUtils.isEmpty(value_weigher_usb)
                                ? '测试'
                                : '$value_weigher_usb',
                            style: XStyleUtils.getTextStyle(
                                fontSize: XTempData.defaultTextFontSize,
                                color: RBColors.reabamColor4),
                          )),
                      onTap: () {
                        XUsbSerialUtils.connectUsbSerialDevice(
                            device: weigher_usb!,
                            callback: (Uint8List? result) {
                              if (result != null) {
                                String r =
                                    XStringUtils.uint8ListToString_gbk(result)
                                        .trim();
                                //XLogUtils.printLog('---usb电子秤result=$r');
                                //S  0,760KGr

                                int nowT = XDateUtils.getCurrentTime_ms();
                                if (r != value_weigher_usb &&
                                    (nowT - timeUsbWeigher) > 2 * 1000) {
                                  timeUsbWeigher = nowT;
                                  setState(() {
                                    value_weigher_usb = r;
                                    XLogUtils.printLog(
                                        '---handleWeigherResultToDouble: ${RBBaseApi.handleWeigherResultToDouble(weigher_usb!.brand ?? '', r)}');
                                  });
                                }
                              }
                            });
                      }),
                  XWidgetUtils.getWidgetGestureDetector(
                      child: XWidgetUtils.getLayoutContainer(
                          backgroundColor: Colors.white,
                          padding: XWidgetUtils.getEdgeInsets(10, 0, 10, 0),
                          child: XWidgetUtils.getWidgetText(
                            '切换品牌',
                            style: XStyleUtils.getTextStyle(
                                fontSize: XTempData.defaultTextFontSize,
                                color: RBColors.reabamColor4),
                          )),
                      onTap: () {
                        value_weigher_usb = null;
                        XUsbSerialUtils.disconnectUsbSerialDevice();
                        startPage(SelectDevicePinaiStatePage(tag: '电子秤'),
                            resultCallback: (dynamic result) {
                          if (result != null) {
                            setState(() {
                              weigher_usb!.brand = result;
                              XUsbSerialUtils.updateNoteUsbDevice(weigher_usb!);
                              _updateUsbSerialDevice();
                            });
                          }
                        });
                      }),
                  XWidgetUtils.getWidgetGestureDetector(
                      child: XWidgetUtils.getLayoutContainer(
                          backgroundColor: Colors.white,
                          padding: XWidgetUtils.getEdgeInsets(10, 0, 10, 0),
                          child: XWidgetUtils.getWidgetText(
                            '删除',
                            style: XStyleUtils.getTextStyle(
                                fontSize: XTempData.defaultTextFontSize,
                                color: RBColors.reabamColor4),
                          )),
                      onTap: () {
                        setState(() {
                          setState(() {
                            XUsbSerialUtils.removeNoteUsbDevice(weigher_usb!);
                            value_weigher_usb = null;
                            XUsbSerialUtils.disconnectUsbSerialDevice();
                            _updateUsbSerialDevice();
                          });
                        });
                      }),
                ]),
                isShowBottomDivider: false,
                isShowTopDivider: true,
              )),
        ]));
  }

  //商米串口电子秤////////////////////////////////////////////////////////////
  Widget _getWidget_serial_weigher_bar_Shangmi() {
    return XWidgetUtils.getLayoutContainer(
        height: 48,
        margin: XWidgetUtils.getEdgeInsets(XTempData.defaultPageMarginLeft, 10,
            XTempData.defaultPageMarginRight, 0),
        padding: XWidgetUtils.getEdgeInsets(10, 0, 0, 0),
        decoration: XWidgetUtils.getBoxDecoration(
            backgroundColor: Colors.white,
            //border: Border.all(width: 0.5, color: XColorUtils.dividerColor),
            borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(10),
              topRight: Radius.circular(10),
              bottomLeft: Radius.circular(10),
              bottomRight: Radius.circular(10),
            )),
        child: XWidgetUtils.getLayoutRow(children: [
          XWidgetUtils.getLayoutExpanded(XWidgetUtils.getWidgetText('是否使用串口电子秤',
              style: XStyleUtils.getTextStyle(
                  fontSize: XTempData.defaultTextFontSize,
                  color: XColorUtils.color333333))),
          XWidgetUtils.getWidgetSwitch(
              currentValue: RBConfigs.isUserShangMiSerialWeigher,
              onChanged: (bool result) {
                setState(() {
                  RBConfigs.isUserShangMiSerialWeigher = result;
                  XSharePreferencesUtils.saveBool(
                      RBConfigs.SP_isUseShangMiSerialWeigher,
                      RBConfigs.isUserShangMiSerialWeigher);
                });
              })
        ]));
  }

  //蓝牙打印机////////////////////////////////////////////////////////////
  Widget _getWidget_printer_bar_Shangmi() {
    return XWidgetUtils.getLayoutContainer(
        height: 48,
        margin: XWidgetUtils.getEdgeInsets(XTempData.defaultPageMarginLeft, 10,
            XTempData.defaultPageMarginRight, 0),
        padding: XWidgetUtils.getEdgeInsets(10, 0, 0, 0),
        decoration: XWidgetUtils.getBoxDecoration(
            backgroundColor: Colors.white,
            //border: Border.all(width: 0.5, color: XColorUtils.dividerColor),
            borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(10),
              topRight: Radius.circular(10),
              bottomLeft: Radius.circular(10),
              bottomRight: Radius.circular(10),
            )),
        child: XWidgetUtils.getLayoutRow(children: [
          XWidgetUtils.getLayoutExpanded(XWidgetUtils.getWidgetText('商米内置打印机',
              style: XStyleUtils.getTextStyle(
                  fontSize: XTempData.defaultTextFontSize,
                  color: XColorUtils.color333333))),
          XWidgetUtils.getWidgetButtonText(
              text: '测试',
              buttonStyle: RBStyles.buttonStyle_reabamColor4_defaultSize(),
              onPressed: () {
                XFlutterPluginUtils.printMsgByShangMi('测试打印');
                XFlutterPluginUtils.cutPaperByShangMi();
              }),
          XWidgetUtils.getWidgetSwitch(
              currentValue: RBConfigs.isUserShangMiPrint,
              onChanged: (bool result) {
                setState(() {
                  RBConfigs.isUserShangMiPrint = result;
                  XSharePreferencesUtils.saveBool(
                      RBConfigs.SP_isUseShangMiPrinter,
                      RBConfigs.isUserShangMiPrint);
                });
              })
        ]));
  }

  //蓝牙
  Widget _getWidget_printer_bar_bluetooth() {
    List<Widget> widgetList = [];
    widgetList.add(XWidgetUtils.getXBarForLeftRightDefault(
      leftText: '蓝牙打印机',
      rightText: '添加设备',
      rightTextStyle: XStyleUtils.getTextStyle(
          fontSize: XTempData.defaultTextFontSize,
          color: RBColors.reabamColor4),
      rightWidget: XImageUtils.getImageWidgetWithAsset('nav_arrow_right.png',
          width: RBConfigs.image_nav_arrow_right_width,
          height: RBConfigs.image_nav_arrow_right_height),
      isShowBottomDivider: false,
      onPressed: () {
        startPage(ScanBleDeviceStatePage(), resultCallback: (dynamic result) {
          //返回扫描选择的蓝牙设备
          if (result != null) {
            XBaseDevice device = result;
            device.customType = RBConfigs.BluetoothPrinter;
            //连接设备
            XBluetoothBLEUtils.addDevice(device);
          }

          //更新ui
          setState(() {
            _updateBluetoothDevice();
          });
        });
      },
    ));

    //蓝牙设备list
    widgetList.add(_getPrinterListView_bluetooth());

    return XWidgetUtils.getXLayoutRoundedRect(
        margin: XWidgetUtils.getEdgeInsets(XTempData.defaultPageMarginLeft, 10,
            XTempData.defaultPageMarginRight, 0),
        child: XWidgetUtils.getLayoutColumn(children: widgetList));
  }

  //usb
  Widget _getWidget_printer_bar_usb() {
    List<Widget> widgetList = [];
    widgetList.add(XWidgetUtils.getXBarForLeftRightDefault(
      leftText: 'USB打印机',
      rightText: '添加设备',
      rightTextStyle: XStyleUtils.getTextStyle(
          fontSize: XTempData.defaultTextFontSize,
          color: RBColors.reabamColor4),
      rightWidget: XImageUtils.getImageWidgetWithAsset('nav_arrow_right.png',
          width: RBConfigs.image_nav_arrow_right_width,
          height: RBConfigs.image_nav_arrow_right_height),
      isShowBottomDivider: false,
      onPressed: () {
        startPage(ScanUsbDeviceStatePage(RBConfigs.USBPrinter),
            resultCallback: (dynamic result) {
          //返回扫描选择的蓝牙设备
          if (result != null) {
            //更新ui
            setState(() {
              _updateUsbDevice();
            });
          }
        });
      },
    ));

    //usb设备list
    widgetList.add(_getPrinterListView_usb());

    return XWidgetUtils.getXLayoutRoundedRect(
        margin: XWidgetUtils.getEdgeInsets(XTempData.defaultPageMarginLeft, 10,
            XTempData.defaultPageMarginRight, 0),
        child: XWidgetUtils.getLayoutColumn(children: widgetList));
  }

  //网络打印
  Widget _getWidget_printer_bar_ip() {
    List<Widget> widgetList = [];
    widgetList.add(XWidgetUtils.getXBarForLeftRightDefault(
      leftText: '网络打印机',
      rightText: '添加设备',
      rightTextStyle: XStyleUtils.getTextStyle(
          fontSize: XTempData.defaultTextFontSize,
          color: RBColors.reabamColor4),
      rightWidget: XImageUtils.getImageWidgetWithAsset('nav_arrow_right.png',
          width: RBConfigs.image_nav_arrow_right_width,
          height: RBConfigs.image_nav_arrow_right_height),
      isShowBottomDivider: false,
      onPressed: () {
        startPage(EditDeviceStatePage(tag: RBConfigs.IPPrinter),
            resultCallback: (dynamic result) {
          if (result != null) {
            //更新ui
            setState(() {
              _updateSocketDevice();
            });
          }
        });
      },
    ));

    widgetList.add(_getPrinterListView_ip());

    return XWidgetUtils.getXLayoutRoundedRect(
        margin: XWidgetUtils.getEdgeInsets(XTempData.defaultPageMarginLeft, 10,
            XTempData.defaultPageMarginRight, 0),
        child: XWidgetUtils.getLayoutColumn(children: widgetList));
  }

  //远程打印设备,如:快麦云打印
  Widget _getWidget_printer_bar_kuaimaiCloudPrint() {
    List<Widget> widgetList = [];
    widgetList.add(XWidgetUtils.getXBarForLeftRightDefault(
      leftText: '云打印机',
      rightText: '添加设备',
      rightTextStyle: XStyleUtils.getTextStyle(
          fontSize: XTempData.defaultTextFontSize,
          color: RBColors.reabamColor4),
      rightWidget: XImageUtils.getImageWidgetWithAsset('nav_arrow_right.png',
          width: RBConfigs.image_nav_arrow_right_width,
          height: RBConfigs.image_nav_arrow_right_height),
      isShowBottomDivider: false,
      onPressed: () {
        startPage(EditDeviceStatePage(tag: RBConfigs.CloudPrinter),
            resultCallback: (dynamic result) {
          if (result != null) {
            //更新ui
            setState(() {
              _updateRemotePrintDevice();
            });
          }
        });
      },
    ));

    widgetList.add(_getPrinterListView_remoteDevice());

    return XWidgetUtils.getXLayoutRoundedRect(
        margin: XWidgetUtils.getEdgeInsets(XTempData.defaultPageMarginLeft, 10,
            XTempData.defaultPageMarginRight, 10),
        child: XWidgetUtils.getLayoutColumn(children: widgetList));
  }

  //打印机列表////////////////////////////////////////////////////////////
  Widget _getPrinterListView_bluetooth() {
    return XWidgetUtils.getWidgetListView(
        shrinkWrap: true,
        listData: printerList_bluetooth,
        listItemWidgetFunction: (BuildContext context, int index) {
          XBaseDevice printerItem = printerList_bluetooth[index];
          String serialNumber = printerItem.serialNumber;
          List<XBaseDeviceScene>? scenes = printerItem.scenes;

          StringBuffer stringBuffer = StringBuffer();
          if (scenes != null) {
            for (int i = 0; i < scenes.length; i++) {
              XBaseDeviceScene scene = scenes[i];
              if (i == scenes.length - 1) {
                stringBuffer.write(scene.name);
              } else {
                stringBuffer.write('${scene.name}, ');
              }
            }
          }

          if (stringBuffer.isEmpty) {
            stringBuffer.write('请选择打印场景');
          }

          Widget leftW = XWidgetUtils.getLayoutExpanded(
              XWidgetUtils.getLayoutColumn(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                XWidgetUtils.getLayoutRow(children: [
                  XWidgetUtils.getWidgetText(printerItem.deviceName ?? '',
                      style: XStyleUtils.getTextStyle(
                          fontSize: XTempData.defaultTextFontSize,
                          color: XColorUtils.color333333)),
                  XWidgetUtils.getXLayoutRoundedRect(
                    margin: XWidgetUtils.getEdgeInsets(10, 0, 0, 0),
                    padding: XWidgetUtils.getEdgeInsets(5, 0, 5, 0),
                    alignment: Alignment.center,
                    backgroundColor: XColorUtils.color666666,
                    child: XWidgetUtils.getWidgetText('$serialNumber号',
                        style: XStyleUtils.getTextStyle(
                          fontSize: XTempData.defaultMiniTextFontSize,
                          color: Colors.white,
                          lineHeight: 1,
                        )),
                    radius: 3,
                  )
                ]),
                XWidgetUtils.getWidgetText(
                  stringBuffer.toString(),
                  style: XStyleUtils.getTextStyle(
                      fontSize: XTempData.defaultSmallTextFontSize,
                      color: XColorUtils.color666666),
                  padding: XWidgetUtils.getEdgeInsets(0, 5, 0, 0),
                ),
              ]));
          Widget rightW = XWidgetUtils.getLayoutRow(children: [
            XWidgetUtils.getWidgetButtonText(
                text: printerItem.isConnected ? '测试' : '(正在连接中)',
                buttonStyle: printerItem.isConnected
                    ? RBStyles.buttonStyle_reabamColor4_defaultSize()
                    : XStyleUtils.getButtonStyle(
                        fontSize: XTempData.defaultTextFontSize,
                        fontColor: XColorUtils.color999999),
                onPressed: () {
                  if (printerItem.printCommandType == 0) {
                    //esc
                    XBluetoothBLEUtils.sendMsgToDevice_test(
                      bluetoothAddress: printerItem.bluetoothAddress!,
                      text:
                          '${printerItem.deviceName},${printerItem.bluetoothAddress} 测试打印!',
                    );
                  } else {
                    //tspl

                    XBeanLabelRow labelText1 = XBeanLabelRow(
                      isUserMarkXY: false,
                      startX_dot: 100,
                      startY_dot: 100,
                      paddingTop_Y_dot: 0,
                      isDrawTable: false,
                      line_thickness: 2,
                      labelColumnTextList: [
                        XBeanLabelColumnText(
                            isAutoFixColumnWidth: true,
                            column_textSize_totalBytesLength: 5,
                            column_space_bytes: 0,
                            textType: 0,
                            text: "测试",
                            textSize: 1,
                            align: 0,
                            isShowBarcodeText: true,
                            isBarQrcodeMaxHeight: false,
                            rotation: 0),
                        XBeanLabelColumnText(
                            isAutoFixColumnWidth: true,
                            column_textSize_totalBytesLength: 6,
                            column_space_bytes: 0,
                            textType: 0,
                            text: "0/0",
                            textSize: 0,
                            align: 1,
                            isShowBarcodeText: true,
                            isBarQrcodeMaxHeight: false,
                            rotation: 0),
                        XBeanLabelColumnText(
                            isAutoFixColumnWidth: true,
                            column_textSize_totalBytesLength: 10,
                            column_space_bytes: 1,
                            textType: 0,
                            text: "123456789012345",
                            textSize: 0,
                            align: 2,
                            isShowBarcodeText: true,
                            isBarQrcodeMaxHeight: false,
                            rotation: 0)
                      ],
                    );
                    XBeanLabelRow labelText2 = XBeanLabelRow(
                      isUserMarkXY: false,
                      startX_dot: 8,
                      startY_dot: 8,
                      paddingTop_Y_dot: 0,
                      isDrawTable: false,
                      line_thickness: 2,
                      labelColumnTextList: [
                        XBeanLabelColumnText(
                            isAutoFixColumnWidth: true,
                            column_textSize_totalBytesLength: 10,
                            column_space_bytes: 0,
                            textType: 2,
                            text: "1234567890",
                            textSize: 0,
                            align: 0,
                            isShowBarcodeText: true,
                            isBarQrcodeMaxHeight: false,
                            rotation: 0),
                        XBeanLabelColumnText(
                            isAutoFixColumnWidth: true,
                            column_textSize_totalBytesLength: 10,
                            column_space_bytes: 0,
                            textType: 1,
                            text: "1234567890",
                            textSize: 0,
                            align: 0,
                            isShowBarcodeText: true,
                            isBarQrcodeMaxHeight: false,
                            rotation: 0)
                      ],
                    );

                    String printCommand = XPrinterCommandUtils.printLabelTSPL(
                      40,
                      30,
                      2,
                      200,
                      [labelText1, labelText2],
                    );

                    XBluetoothBLEUtils.sendMsgToDevice_test(
                      bluetoothAddress: printerItem.bluetoothAddress!,
                      text: printCommand,
                    );
                  }
                }),
            XWidgetUtils.getWidgetButtonText(
                text: '编辑',
                buttonStyle: RBStyles.buttonStyle_reabamColor4_defaultSize(),
                onPressed: () {
                  //跳转到编辑打印机界面
                  startPage(
                      EditDeviceStatePage(
                          tag: RBConfigs.BluetoothPrinter,
                          currentDevice: printerItem),
                      resultCallback: (dynamic result) {
                    if (result != null) {
                      //更新ui
                      setState(() {
                        _updateBluetoothDevice();
                      });
                    }
                  });
                }),
          ]);

          return XWidgetUtils.getXBarForLeftRightWidget(
            leftWidget: leftW,
            rightWidget: rightW,
            isShowBottomDivider: false,
            isShowTopDivider: true,
            height: RBConfigs.deviceBarHeight,
          );
        });
  }

  Widget _getPrinterListView_usb() {
    return XWidgetUtils.getWidgetListView(
        shrinkWrap: true,
        listData: printerList_usb,
        listItemWidgetFunction: (BuildContext context, int index) {
          XBaseDevice printerItem = printerList_usb[index];
          String serialNumber = printerItem.serialNumber;
          List<XBaseDeviceScene>? scenes = printerItem.scenes;

          StringBuffer stringBuffer = StringBuffer();
          if (scenes != null) {
            for (int i = 0; i < scenes.length; i++) {
              XBaseDeviceScene scene = scenes[i];
              if (i == scenes.length - 1) {
                stringBuffer.write(scene.name);
              } else {
                stringBuffer.write('${scene.name}, ');
              }
            }
          }

          if (stringBuffer.isEmpty) {
            stringBuffer.write('请选择打印场景');
          }

          Widget leftW = XWidgetUtils.getLayoutExpanded(
              XWidgetUtils.getLayoutColumn(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                XWidgetUtils.getLayoutRow(children: [
                  XWidgetUtils.getWidgetText(printerItem.deviceName ?? '',
                      style: XStyleUtils.getTextStyle(
                          fontSize: XTempData.defaultTextFontSize,
                          color: XColorUtils.color333333)),
                  XWidgetUtils.getXLayoutRoundedRect(
                    margin: XWidgetUtils.getEdgeInsets(10, 0, 0, 0),
                    padding: XWidgetUtils.getEdgeInsets(5, 0, 5, 0),
                    alignment: Alignment.center,
                    backgroundColor: XColorUtils.color666666,
                    child: XWidgetUtils.getWidgetText('$serialNumber号',
                        style: XStyleUtils.getTextStyle(
                          fontSize: XTempData.defaultMiniTextFontSize,
                          color: Colors.white,
                          lineHeight: 1,
                        )),
                    radius: 3,
                  )
                ]),
                XWidgetUtils.getWidgetText(
                  stringBuffer.toString(),
                  style: XStyleUtils.getTextStyle(
                      fontSize: XTempData.defaultSmallTextFontSize,
                      color: XColorUtils.color666666),
                  padding: XWidgetUtils.getEdgeInsets(0, 5, 0, 0),
                ),
              ]));
          Widget rightW = XWidgetUtils.getLayoutRow(children: [
            XWidgetUtils.getWidgetButtonText(
                text: '测试',
                buttonStyle: RBStyles.buttonStyle_reabamColor4_defaultSize(),
                onPressed: () {
                  if (printerItem.printCommandType == 0) {
                    //esc
                    XUsbUtils.sendMessage_test(
                      printerItem,
                      '${printerItem.deviceName} 测试打印!',
                    );
                  } else {
                    //tspl
                    XBeanLabelRow labelText1 = XBeanLabelRow(
                      isUserMarkXY: false,
                      startX_dot: 100,
                      startY_dot: 100,
                      paddingTop_Y_dot: 0,
                      isDrawTable: false,
                      line_thickness: 2,
                      labelColumnTextList: [
                        XBeanLabelColumnText(
                            isAutoFixColumnWidth: true,
                            column_textSize_totalBytesLength: 5,
                            column_space_bytes: 0,
                            textType: 0,
                            text: "测试",
                            textSize: 1,
                            align: 0,
                            isShowBarcodeText: true,
                            isBarQrcodeMaxHeight: false,
                            rotation: 0),
                        XBeanLabelColumnText(
                            isAutoFixColumnWidth: true,
                            column_textSize_totalBytesLength: 6,
                            column_space_bytes: 0,
                            textType: 0,
                            text: "0/0",
                            textSize: 0,
                            align: 1,
                            isShowBarcodeText: true,
                            isBarQrcodeMaxHeight: false,
                            rotation: 0),
                        XBeanLabelColumnText(
                            isAutoFixColumnWidth: true,
                            column_textSize_totalBytesLength: 10,
                            column_space_bytes: 1,
                            textType: 0,
                            text: "123456789012345",
                            textSize: 0,
                            align: 2,
                            isShowBarcodeText: true,
                            isBarQrcodeMaxHeight: false,
                            rotation: 0)
                      ],
                    );
                    XBeanLabelRow labelText2 = XBeanLabelRow(
                      isUserMarkXY: false,
                      startX_dot: 8,
                      startY_dot: 8,
                      paddingTop_Y_dot: 0,
                      isDrawTable: false,
                      line_thickness: 2,
                      labelColumnTextList: [
                        XBeanLabelColumnText(
                            isAutoFixColumnWidth: true,
                            column_textSize_totalBytesLength: 10,
                            column_space_bytes: 0,
                            textType: 2,
                            text: "1234567890",
                            textSize: 0,
                            align: 0,
                            isShowBarcodeText: true,
                            isBarQrcodeMaxHeight: false,
                            rotation: 0),
                        XBeanLabelColumnText(
                            isAutoFixColumnWidth: true,
                            column_textSize_totalBytesLength: 10,
                            column_space_bytes: 0,
                            textType: 1,
                            text: "1234567890",
                            textSize: 0,
                            align: 0,
                            isShowBarcodeText: true,
                            isBarQrcodeMaxHeight: false,
                            rotation: 0)
                      ],
                    );

                    String printCommand = XPrinterCommandUtils.printLabelTSPL(
                      40,
                      30,
                      2,
                      200,
                      [labelText1, labelText2],
                    );

                    XUsbUtils.sendMessage_test(
                      printerItem,
                      printCommand,
                    );
                  }
                }),
            XWidgetUtils.getWidgetButtonText(
                text: '编辑',
                buttonStyle: RBStyles.buttonStyle_reabamColor4_defaultSize(),
                onPressed: () {
                  //跳转到编辑打印机界面
                  startPage(
                      EditDeviceStatePage(
                          tag: RBConfigs.USBPrinter,
                          currentDevice: printerItem),
                      resultCallback: (dynamic result) {
                    if (result != null) {
                      //更新ui
                      setState(() {
                        _updateUsbDevice();
                      });
                    }
                  });
                }),
          ]);

          return XWidgetUtils.getXBarForLeftRightWidget(
            leftWidget: leftW,
            rightWidget: rightW,
            isShowBottomDivider: false,
            isShowTopDivider: true,
            height: RBConfigs.deviceBarHeight,
          );
        });
  }

  Widget _getPrinterListView_ip() {
    return XWidgetUtils.getWidgetListView(
      shrinkWrap: true,
      listData: printerList_socket,
      listItemWidgetFunction: (BuildContext context, int index) {
        XBaseDevice printerItem = printerList_socket[index];
        String serialNumber = printerItem.serialNumber;
        List<XBaseDeviceScene>? scenes = printerItem.scenes;

        StringBuffer stringBuffer = StringBuffer();
        if (scenes != null) {
          for (int i = 0; i < scenes.length; i++) {
            XBaseDeviceScene scene = scenes[i];
            if (i == scenes.length - 1) {
              stringBuffer.write(scene.name);
            } else {
              stringBuffer.write('${scene.name}, ');
            }
          }
        }

        if (stringBuffer.isEmpty) {
          stringBuffer.write('请选择打印场景');
        }

        Widget leftW = XWidgetUtils.getLayoutExpanded(
            XWidgetUtils.getLayoutColumn(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
              XWidgetUtils.getLayoutRow(children: [
                XWidgetUtils.getWidgetText(printerItem.deviceName ?? '',
                    style: XStyleUtils.getTextStyle(
                        fontSize: XTempData.defaultTextFontSize,
                        color: XColorUtils.color333333)),
                XWidgetUtils.getXLayoutRoundedRect(
                  margin: XWidgetUtils.getEdgeInsets(10, 0, 0, 0),
                  padding: XWidgetUtils.getEdgeInsets(5, 0, 5, 0),
                  alignment: Alignment.center,
                  backgroundColor: XColorUtils.color666666,
                  child: XWidgetUtils.getWidgetText('$serialNumber号',
                      style: XStyleUtils.getTextStyle(
                        fontSize: XTempData.defaultMiniTextFontSize,
                        color: Colors.white,
                        lineHeight: 1,
                      )),
                  radius: 3,
                )
              ]),
              XWidgetUtils.getWidgetText(
                stringBuffer.toString(),
                style: XStyleUtils.getTextStyle(
                    fontSize: XTempData.defaultSmallTextFontSize,
                    color: XColorUtils.color666666),
                padding: XWidgetUtils.getEdgeInsets(0, 5, 0, 0),
              ),
            ]));
        Widget rightW = XWidgetUtils.getLayoutRow(children: [
          XWidgetUtils.getWidgetButtonText(
              text: printerItem.isSocketShortConnect
                  ? '测试'
                  : (printerItem.isConnected ? '测试' : '(正在连接中)'),
              buttonStyle: printerItem.isSocketShortConnect
                  ? RBStyles.buttonStyle_reabamColor4_defaultSize()
                  : (printerItem.isConnected
                      ? RBStyles.buttonStyle_reabamColor4_defaultSize()
                      : XStyleUtils.getButtonStyle(
                          fontSize: XTempData.defaultTextFontSize,
                          fontColor: XColorUtils.color999999)),
              onPressed: () {
                XBaseQueueMessage msg = XBaseQueueMessage(
                  msgId: 'socketPrinter_${XDateUtils.getCurrentTime_ms()}',
                  ip: printerItem.ip!,
                  port: printerItem.port,
                );

                if (printerItem.printCommandType == 0) {
                  //esc
                  msg.message_Uint8List = XStringUtils.stringToUint8List_gbk(
                      '${printerItem.deviceName},${printerItem.ip} 测试打印!\n');
                } else {
                  //tspl
                  XBeanLabelRow labelText1 = XBeanLabelRow(
                    isUserMarkXY: false,
                    startX_dot: 100,
                    startY_dot: 100,
                    paddingTop_Y_dot: 0,
                    isDrawTable: false,
                    line_thickness: 2,
                    labelColumnTextList: [
                      XBeanLabelColumnText(
                          isAutoFixColumnWidth: true,
                          column_textSize_totalBytesLength: 5,
                          column_space_bytes: 0,
                          textType: 0,
                          text: "测试",
                          textSize: 1,
                          align: 0,
                          isShowBarcodeText: true,
                          isBarQrcodeMaxHeight: false,
                          rotation: 0),
                      XBeanLabelColumnText(
                          isAutoFixColumnWidth: true,
                          column_textSize_totalBytesLength: 6,
                          column_space_bytes: 0,
                          textType: 0,
                          text: "0/0",
                          textSize: 0,
                          align: 1,
                          isShowBarcodeText: true,
                          isBarQrcodeMaxHeight: false,
                          rotation: 0),
                      XBeanLabelColumnText(
                          isAutoFixColumnWidth: true,
                          column_textSize_totalBytesLength: 10,
                          column_space_bytes: 1,
                          textType: 0,
                          text: "123456789012345",
                          textSize: 0,
                          align: 2,
                          isShowBarcodeText: true,
                          isBarQrcodeMaxHeight: false,
                          rotation: 0)
                    ],
                  );
                  XBeanLabelRow labelText2 = XBeanLabelRow(
                    isUserMarkXY: false,
                    startX_dot: 8,
                    startY_dot: 8,
                    paddingTop_Y_dot: 0,
                    isDrawTable: false,
                    line_thickness: 2,
                    labelColumnTextList: [
                      XBeanLabelColumnText(
                          isAutoFixColumnWidth: true,
                          column_textSize_totalBytesLength: 10,
                          column_space_bytes: 0,
                          textType: 2,
                          text: "1234567890",
                          textSize: 0,
                          align: 0,
                          isShowBarcodeText: true,
                          isBarQrcodeMaxHeight: false,
                          rotation: 0),
                      XBeanLabelColumnText(
                          isAutoFixColumnWidth: true,
                          column_textSize_totalBytesLength: 10,
                          column_space_bytes: 0,
                          textType: 1,
                          text: "1234567890",
                          textSize: 0,
                          align: 0,
                          isShowBarcodeText: true,
                          isBarQrcodeMaxHeight: false,
                          rotation: 0)
                    ],
                  );
                  String printCommand = XPrinterCommandUtils.printLabelTSPL(
                    40,
                    30,
                    2,
                    200,
                    [labelText1, labelText2],
                  );
                  msg.message_Uint8List =
                      XStringUtils.stringToUint8List_gbk(printCommand);
                }

                XSocketUtils.sendMsgToQueue(msg);
              }),
          XWidgetUtils.getWidgetButtonText(
              text: '编辑',
              buttonStyle: RBStyles.buttonStyle_reabamColor4_defaultSize(),
              onPressed: () {
                //跳转到编辑打印机界面
                startPage(
                    EditDeviceStatePage(
                        tag: RBConfigs.IPPrinter, currentDevice: printerItem),
                    resultCallback: (dynamic result) {
                  if (result != null) {
                    //更新ui
                    setState(() {
                      _updateSocketDevice();
                    });
                  }
                });
              }),
        ]);

        return XWidgetUtils.getXBarForLeftRightWidget(
          leftWidget: leftW,
          rightWidget: rightW,
          isShowBottomDivider: false,
          isShowTopDivider: true,
          height: RBConfigs.deviceBarHeight,
        );
      },
    );
  }

  Widget _getPrinterListView_remoteDevice() {
    return XWidgetUtils.getWidgetListView(
      shrinkWrap: true,
      listData: printerList_cloudDevice,
      listItemWidgetFunction: (BuildContext context, int index) {
        XBaseDevice printerItem = printerList_cloudDevice[index];
        String serialNumber = printerItem.serialNumber;
        List<XBaseDeviceScene>? scenes = printerItem.scenes;

        StringBuffer stringBuffer = StringBuffer();
        if (scenes != null) {
          for (int i = 0; i < scenes.length; i++) {
            XBaseDeviceScene scene = scenes[i];
            if (i == scenes.length - 1) {
              stringBuffer.write(scene.name);
            } else {
              stringBuffer.write('${scene.name}, ');
            }
          }
        }

        if (stringBuffer.isEmpty) {
          stringBuffer.write('请选择打印场景');
        }

        Widget leftW = XWidgetUtils.getLayoutExpanded(
            XWidgetUtils.getLayoutColumn(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
              XWidgetUtils.getLayoutRow(children: [
                XWidgetUtils.getWidgetText(
                    '${printerItem.deviceName}(${printerItem.deviceUUID})',
                    style: XStyleUtils.getTextStyle(
                        fontSize: XTempData.defaultTextFontSize,
                        color: XColorUtils.color333333)),
                XWidgetUtils.getXLayoutRoundedRect(
                  margin: XWidgetUtils.getEdgeInsets(10, 0, 0, 0),
                  padding: XWidgetUtils.getEdgeInsets(5, 0, 5, 0),
                  alignment: Alignment.center,
                  backgroundColor: XColorUtils.color666666,
                  child: XWidgetUtils.getWidgetText('$serialNumber号',
                      style: XStyleUtils.getTextStyle(
                        fontSize: XTempData.defaultMiniTextFontSize,
                        color: Colors.white,
                        lineHeight: 1,
                      )),
                  radius: 3,
                )
              ]),
              XWidgetUtils.getWidgetText(
                stringBuffer.toString(),
                style: XStyleUtils.getTextStyle(
                    fontSize: XTempData.defaultSmallTextFontSize,
                    color: XColorUtils.color666666),
                padding: XWidgetUtils.getEdgeInsets(0, 5, 0, 0),
              ),
            ]));
        Widget rightW = XWidgetUtils.getLayoutRow(children: [
          XWidgetUtils.getWidgetButtonText(
              text: '编辑',
              buttonStyle: RBStyles.buttonStyle_reabamColor4_defaultSize(),
              onPressed: () {
                //跳转到编辑打印机界面
                startPage(
                    EditDeviceStatePage(
                        tag: RBConfigs.CloudPrinter,
                        currentDevice: printerItem),
                    resultCallback: (dynamic result) {
                  if (result != null) {
                    //更新ui
                    setState(() {
                      _updateRemotePrintDevice();
                    });
                  }
                });
              }),
        ]);

        return XWidgetUtils.getXBarForLeftRightWidget(
          leftWidget: leftW,
          rightWidget: rightW,
          isShowBottomDivider: false,
          isShowTopDivider: true,
          height: RBConfigs.deviceBarHeight,
        );
      },
    );
  }

  void _updateBluetoothDevice() {
    //
    printerList_bluetooth.clear();
    weigher_bluetooth = null;

    Set<XBaseDevice> bluetoothBLEDeviceList =
        XBluetoothBLEUtils.bluetoothBLEDeviceList;
    for (XBaseDevice item in bluetoothBLEDeviceList) {
      if (RBConfigs.BluetoothPrinter == item.customType) {
        printerList_bluetooth.add(item);
      } else if (RBConfigs.BluetoothWeigher == item.customType) {
        weigher_bluetooth = item;
      }
    }
  }

  void _updateUsbDevice() {
    //
    printerList_usb.clear();

    Set<XBaseDevice> usbDeviceList = XUsbUtils.usbDeviceList;
    for (XBaseDevice item in usbDeviceList) {
      if (RBConfigs.USBPrinter == item.customType) {
        printerList_usb.add(item);
      }
    }
  }

  void _updateUsbSerialDevice() {
    weigher_usb = null;
    Set<XBaseDevice> usbDeviceList = XUsbSerialUtils.usbSerialDeviceList;
    for (XBaseDevice item in usbDeviceList) {
      if (RBConfigs.UsbSerialWeigher == item.customType) {
        weigher_usb = item;
        break;
      }
    }
  }
}
